#include <OES.hpp>

#include <Renderer.hpp>

namespace Renderer
{
	class TContextOES : public TAbstractContext
	{
	private:
		EGLDisplay mEglDisplay;
		EGLConfig mEglConfig;
		EGLContext mEglContext;
		EGLContext mEglSurface;
		EGLint     mConfig;
	public:
		TContextOES(IDK::Viewport viewport)
		{
			EGLNativeWindowType hwnd = (EGLNativeWindowType)viewport->GetHWND()->GetPointer();
			EGLNativeDisplayType dc = (EGLNativeDisplayType)viewport->GetDC()->GetPointer();

			mEglDisplay = eglGetDisplay(dc);

			if(mEglDisplay == EGL_NO_DISPLAY)
			{
				iError("No display");
				//error
			}

			if(!eglInitialize(mEglDisplay, 0, 0))
			{
				iError("Initialize");
				//error
			}

			if(!eglBindAPI(EGL_OPENGL_ES_API))
			{
				iError("Bind API");
				//error
			}

			const EGLint configAttribs[] =
			{
				EGL_BUFFER_SIZE,		0,
				EGL_DEPTH_SIZE,			16,
				EGL_SURFACE_TYPE,		EGL_WINDOW_BIT,
				EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
				EGL_SAMPLE_BUFFERS,		0,
				EGL_NONE
			};

			EGLint numConfigs;

			if(!eglChooseConfig(mEglDisplay, configAttribs, &mEglConfig, 1, &numConfigs))
			{
				iError("ChooseConfig");
			}

			// Find an EGL config
			eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_CONFIG_ID, &mConfig);

			// Attempt to create a context
			const EGLint contextAttribs[] =
			{
				EGL_CONTEXT_CLIENT_VERSION, 2,
				EGL_NONE
			};

			mEglContext = eglCreateContext(mEglDisplay, mEglConfig, 0, contextAttribs);
			mEglSurface = eglCreateWindowSurface(mEglDisplay, mEglConfig, hwnd, 0);	
			
			if(!eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext))
			{
				iError("MakeCurrent");
			}

			eglSwapInterval(mEglDisplay, 1);

			glValid(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
		}

		virtual ~TContextOES()
		{
			eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
			eglDestroySurface(mEglDisplay, mEglSurface);
			eglDestroyContext(mEglDisplay, mEglContext);
			eglTerminate(mEglDisplay);
		}

		virtual void SwapBuffers()
		{
			eglSwapBuffers(mEglDisplay, mEglSurface);
		}
	};
}